package com.pybox.spec;

import com.pybox.entity.TGroups;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 描述：TGroups Specification
 *
 * @author wuyingkai
 * @date 2018-09-15
 */


public class TGroupsSpec implements Specification<TGroups> {

    private Map<String, String> params;

    public TGroupsSpec(Map<String, String> params) {
        this.params = params;
    }

    @Override
    public Predicate toPredicate(Root<TGroups> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {


        String customerId = this.params.get("customerId");
        String name = this.params.get("name");
        String comments = this.params.get("comments");
        String timeChannels = this.params.get("timeChannels");
        String deleted = this.params.get("deleted");
        String ctime = this.params.get("ctime");
        String utime = this.params.get("utime");
        String createby = this.params.get("createby");
        String updateby = this.params.get("updateby");
        List<Predicate> ps = new ArrayList<>();

        ps.add(criteriaBuilder.equal(root.get("deleted"), 0));


        if (!StringUtils.isEmpty(customerId)) {
            ps.add(criteriaBuilder.equal(root.get("customerId"), customerId));
        }
        if (!StringUtils.isEmpty(name)) {
            ps.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
        }
        if (!StringUtils.isEmpty(comments)) {
            ps.add(criteriaBuilder.like(root.get("comments"), "%" + comments + "%"));
        }
        if (!StringUtils.isEmpty(timeChannels)) {
            ps.add(criteriaBuilder.like(root.get("timeChannels"), "%" + timeChannels + "%"));
        }
        if (!StringUtils.isEmpty(ctime)) {
            ps.add(criteriaBuilder.like(root.get("ctime"), "%" + ctime + "%"));
        }
        if (!StringUtils.isEmpty(utime)) {
            ps.add(criteriaBuilder.like(root.get("utime"), "%" + utime + "%"));
        }
        if (!StringUtils.isEmpty(createby)) {
            ps.add(criteriaBuilder.like(root.get("createby"), "%" + createby + "%"));
        }
        if (!StringUtils.isEmpty(updateby)) {
            ps.add(criteriaBuilder.like(root.get("updateby"), "%" + updateby + "%"));
        }

        criteriaQuery = criteriaQuery.where(ps.toArray(new Predicate[ps.size()]));

        return criteriaQuery.getRestriction();
    }

}